#include"MyPlayer.h"
int bVideoThreadRunning=0;
void display_video(uint8_t *buffer,int width,int height,SDL_Surface*screen);
int SDL_VIDEO_Thread(void*data){
    int StartTimestamp=0;
    int CheckTimestamp=0;
    SDL_Surface *screen = SDL_SetVideoMode(WINDOWS_WIDTH,WINDOWS_HIGHT,24,SDL_SWSURFACE);
    if(screen){
        printf("SDL initialized %dx%d.\n",WINDOWS_WIDTH,WINDOWS_HIGHT);
    }else{
        printf("SDL initialized Failed.\n");
        exit(0);
    }
    printf("SDL_PLAY_Thread\n");
    bVideoThreadRunning=1;
    while(running||GetVideoPacketLength()>0){
		DATAINFO*pos=GetVideoPacket();
		if(pos!=NULL){
			int DelayTime=1;
			if(StartTimestamp==0){
				StartTimestamp=SDL_GetTicks();
				//CheckTimestamp=pos->timestamp;
			}else{
				int RealDiff=SDL_GetTicks()-StartTimestamp;
				int VideoDiff=pos->timestamp-CheckTimestamp;
				//int Ret=IsVideoFastThenAudio();
				if(VideoDiff>RealDiff){
					DelayTime=VideoDiff-RealDiff;
				}
			}
			if(running)SDL_Delay(DelayTime);
			if(running)display_video(pos->data,pos->width,pos->height,screen);
			av_free(pos->data);
			free(pos);
		}else {
			SDL_Delay(10);
		}
    }
    printf("SDL_PLAY_Thread End\n");
    return 0;
}
void display_video(uint8_t*buffer,int width,int height,SDL_Surface*screen){
#if USE_FFMPEG_SWS
	SDL_Surface*image = NULL;
	image = SDL_CreateRGBSurfaceFrom(buffer, width, height, 24, 3 * width, 0, 0, 0, 0);
	if (SDL_BlitSurface(image, NULL, screen, NULL)<0) {
		fprintf(stderr, "BlitSurface error: %s\n", SDL_GetError());
	}
	SDL_UpdateRect(screen, 0, 0, screen->w, screen->h);
	SDL_FreeSurface(image);
#else    
	SDL_Overlay*image=SDL_CreateYUVOverlay(width,height,SDL_IYUV_OVERLAY,screen);
    SDL_Rect rect={0,0,WINDOWS_WIDTH,WINDOWS_HIGHT};
	image->pixels[0] = buffer;
	image->pixels[1] = buffer+ width*height;
	image->pixels[2] = buffer + width*height*5/4;
	SDL_DisplayYUVOverlay(image,&rect);
	SDL_FreeYUVOverlay(image);
#endif
}

